//
//  HJFriendListController.m
//  KaiChat
//
//  Created by lx on 2023/10/20.
//

#import "HJFriendListController.h"
#import "HJFriendListCell.h"
#import "HJSectionHeaderView.h"
#import "HJFriendListHeaderButton.h"
#import "HJIM.h"
#import "HJUserInfoController.h"
#import "QMUITextField.h"
#import "HJAddFriendController.h"
#import "HJNavigationController.h"

@interface HJFriendListController ()

@property (nonatomic, strong) NSMutableArray *datas;
@property (nonatomic, strong) NSMutableArray *sortKeys;

@end

@implementation HJFriendListController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 180)];
    headerView.backgroundColor = UIColor.whiteColor;
    
    UIView *searchView = [UIView addToView:headerView];
    searchView.backgroundColor = UIColor.tj_F6F6F6Color;
    searchView.addCornerRadius(10);
    [searchView addTapGesturesWithTarget:self action:@selector(tapSearchView)];
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.top.offset(10);
        make.height.offset(40);
    }];
    
    UIImageView *searchIcon = [UIImageView addToView:searchView];
    searchIcon.image = [UIImage imageNamed:@"search_icon"];
    [searchIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(15);
    }];
    
    UILabel *searchTextLabel = [UILabel lableWithSuperView:searchView font:UIFontMake(14) color:UIColor.tj_BEBDCAColor title:@"search" textAlignment:NSTextAlignmentLeft];
    [searchTextLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(searchIcon.mas_right).offset(10);
        make.centerY.offset(0);
    }];
    
    HJFriendListHeaderButton *newFriendButton = [[HJFriendListHeaderButton alloc] init];
    newFriendButton.iconImageView.image = [UIImage imageNamed:@"newFriend"];
    newFriendButton.textLabel.text = @"New Contacts";
    [newFriendButton addTarget:self action:@selector(didClickNewFriendButton) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:newFriendButton];
    [newFriendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.height.offset(60);
        make.top.equalTo(searchView.mas_bottom).offset(10);
    }];
    
    HJFriendListHeaderButton *groupButton = [[HJFriendListHeaderButton alloc] init];
    groupButton.iconImageView.image = [UIImage imageNamed:@"group_icon"];
    groupButton.textLabel.text = @"Groups";
    [groupButton addTarget:self action:@selector(didClickGroupButton) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:groupButton];
    [groupButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.equalTo(newFriendButton);
        make.top.equalTo(newFriendButton.mas_bottom);
    }];
    
    
    self.navigationBar.title = @"Address book";
    self.view.backgroundColor = UIColor.tj_F6F6F6Color;
    self.tableViewStyle = UITableViewStylePlain;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, TabbarSafeBottomMargin, 0);
    self.tableView.tableHeaderView = headerView;
    [self.tableView registerClass:HJFriendListCell.class forCellReuseIdentifier:@"HJFriendListCell"];
    [self.tableView registerClass:HJSectionHeaderView.class forHeaderFooterViewReuseIdentifier:@"HJSectionHeaderView"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = 64;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView setSectionIndexColor:UIColor.tj_333333Color];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(KNavBarHight);
        make.left.right.bottom.offset(0);
    }];
    
    [self loadData];
}

- (void)didClickGroupButton {
    [self.navigationController pushViewControllerWithName:@"HJGroupListController"];
}

- (void)didClickNewFriendButton {
    [self.navigationController pushViewControllerWithName:@"HJApplyListController"];
}
 
- (void)tapSearchView {
    HJNavigationController *navController = [[HJNavigationController alloc] initWithRootViewController:[[HJAddFriendController alloc] init]];
    [self presentViewController:navController animated:YES completion:nil];
}

- (NSMutableArray *)datas {
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}

- (NSMutableArray *)sortKeys {
    if (!_sortKeys) {
        _sortKeys = [NSMutableArray array];
    }
    return _sortKeys;
}

- (void)loadData {
    [[HJIM shareIM].userManager getFriendListsComplete:^(NSArray<HJChatFriendModel *> * _Nullable datas) {
        dispatch_async_main_queue(^{
            [self hiddenLoading];
            [self handleModels:datas];
        });
    }];
}

- (void)handleModels:(NSArray *)models {
    
    NSMutableDictionary *mainDict = [NSMutableDictionary dictionary];
    for (HJChatFriendModel *obj in models) {
        NSString *displayName = obj.showName;
        NSString *firstLetter = [displayName.firstPinYin uppercaseString];
        if (firstLetter.length == 0 || !isalpha([firstLetter characterAtIndex:0])) {
            firstLetter = @"#";
        }
        NSMutableArray *dictMarr = [mainDict valueForKey:firstLetter];
         if (!dictMarr) {
             [mainDict setValue:[NSMutableArray array] forKey:firstLetter];
             dictMarr = [mainDict valueForKey:firstLetter];
         }
        [dictMarr addObject:obj];
    }

    NSArray *nonameList = [mainDict valueForKey:@"#"];
    if (nonameList) {
        [mainDict removeObjectForKey:@"#"];
    }

    [self.datas removeAllObjects];
    [self.sortKeys removeAllObjects];
    
    NSArray *sortKeys = [mainDict.allKeys sortedArrayUsingComparator:^NSComparisonResult(NSString *  _Nonnull obj1, NSString *  _Nonnull obj2) {
        return [obj1 compare:obj2] == NSOrderedDescending;
    }];
        
    [sortKeys enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.datas addObject:@{ @"title": obj, @"datas": mainDict[obj]}];
    }];
    
    self.sortKeys = [NSMutableArray arrayWithArray:sortKeys];
    if (nonameList.count) {
        [self.sortKeys addObject:@"#"];
        [self.datas addObject:@{@"title": @"#", @"datas": nonameList}];
    }
 
    [self.tableView reloadData];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.datas.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *datas = self.datas[section][@"datas"];
    return [datas count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJFriendListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJFriendListCell" forIndexPath:indexPath];
    HJChatFriendModel *model = self.datas[indexPath.section][@"datas"][indexPath.row];
    cell.model = model;
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
 
    HJChatFriendModel *model = self.datas[indexPath.section][@"datas"][indexPath.row];
    HJUserInfoController *infoController = [[HJUserInfoController alloc] init];
    infoController.friendModel = model;
    [self.navigationController pushViewController:infoController];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20;
}

-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return self.sortKeys;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    HJSectionHeaderView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"HJSectionHeaderView"];
    view.titleLabel.text = @"";
    view.contentView.backgroundColor = UIColor.tj_F6F6F6Color;
    view.backgroundColor = UIColor.tj_F6F6F6Color;
    NSString *sectionTitle = self.datas[section][@"title"];
    view.titleLabel.text = sectionTitle;
    view.titleLabel.textColor = UIColor.tj_868391Color;
    view.titleLabel.font = UIFontMake(12);
    return view;
}


- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = UIColor.clearColor;
    return view;
}


@end

